<?php
defined('IN_ZEEGING') or die('Access Denied');
require_once ZEEGING_PATH.'Librarys'.DIRECTORY_SEPARATOR.'ethereum'.DIRECTORY_SEPARATOR.'EthereumApi.php';
class AddressModel extends Model{
	/*
	CREATE TABLE `address` (
	  `merchantid` varchar(50) NOT NULL COMMENT '商户唯一名',
	  `username` varchar(50) NOT NULL COMMENT '商户系统的用户名',
	  `privatekey` varchar(200) NOT NULL COMMENT '私钥',
	  `address` varchar(200) NOT NULL COMMENT '地址',
	  `status` int(11) NOT NULL DEFAULT '0' COMMENT '帐户状态,0为正常状态',
	  `currency` varchar(50) NOT NULL COMMENT '币名称',
	  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='地址和私钥'
	*/
	private $row;

	public function loadAll($merchantId,$currency){
		//总用户量1k以内可以用这个方案，若用户量持续增长则需要考虑其他方案
		$addressArray=array();
		$sql="select * from address where merchantid='$merchantId' and currency='$currency'";
		$res=$this->query($sql);
		while ($row=$this->fetch($res,'object')) {
			array_push($addressArray, $row);
		}
		return $addressArray;
	}

	public function load($mobile,$merchantId,$currency){
		$sql="select * from address where username='$mobile' and merchantid='$merchantId' and currency='$currency'";
		$res=$this->query($sql);
		if($res && $row=$this->fetch($res,'object')){
			$this->row=$row;
			return $this;
		}
		if($this->existMerchantId($merchantId)){
			$this->row=$this->createUser($mobile,$merchantId,$currency);
			return $this;
		}
		return false;	//这里应该抛出错误
	}

	public function loadByAddress($address,$merchantId,$currency){
		$sql="select * from address where `address`='$address' and merchantid='$merchantId' and currency='$currency'";
		$res=$this->query($sql);
		if($res && $row=$this->fetch($res,'object')){
			$this->row=$row;
			return $this;
		}
		return false;	//这里应该抛出错误
	}

	protected function existMerchantId($merchantId){
		if($merchantId=='betcat'){
			return true;
		}
		else{
			return false;
		}
	}

	protected function createUser($mobile,$merchantId,$currency){
		$api=new EthereumApi();
		$newWallet=$api->generateWallet();
		$address=$newWallet->address;
		$privateKey=$newWallet->private;
		$insertSql="INSERT INTO `address`(`merchantid`, `username`, `privatekey`, `address`, `status`, `currency`)
				VALUES ('$merchantId','$mobile','$privateKey','$address',0,'$currency')";
		$id=($this->execute($insertSql) ? $this->fetch($this->query('select @@IDENTITY;')) : null );
		$row=(object)array(
			"merchantid"=>$merchantId,
			"username"=>$mobile,
			"privatekey"=>$privateKey,
			"address"=>$address,
			"status"=>0,
			"currency"=>$currency,
			"id"=>$id
		);
		return !empty($id) ? $row : false;	//false这里应该抛出错误
	}

	public function __get($name){
		return $this->row->$name;
	}
}